package io.renren.common.utils;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

public class FileUtils {


    public static boolean checkFileSize(Long len, int size, String unit) {
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }


    public static void commpressPicCycle(String desPath,
                                         double accuracy) throws IOException {
        File imgFile = new File(desPath);

        boolean flag = checkFileSize(imgFile.length(), 200, "K");
        while (!flag) {
            imgFile = new File(desPath);
            //计算宽高
            BufferedImage bim = ImageIO.read(imgFile);
            int imgWidth = bim.getWidth();
            int imgHeight = bim.getHeight();
            int desWidth = new BigDecimal(imgWidth).multiply(
                    new BigDecimal(accuracy)).intValue();
            int desHeight = new BigDecimal(imgHeight).multiply(
                    new BigDecimal(accuracy)).intValue();
            Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
            flag = checkFileSize(imgFile.length(), 200, "K");
        }
    }

    public static void main(String[] args) {

        try {
            commpressPicCycle("/Users/keyyang/yxjy.jpg", 0.8);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
